<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTTP 请求模拟工具</title>
    <link rel="stylesheet" href="../json/styles.css">
    <link href="https://cdn.bootcdn.net/ajax/libs/font-awesome/6.7.2/css/all.min.css" rel="stylesheet">
    <style>
        /* HTTP工具特定样式 */
        .http-container {
            display: flex;
            flex-direction: column;
            gap: 20px;
        }
        
        .request-section {
            background-color: var(--card-background);
            border-radius: 8px;
            box-shadow: 0 4px 6px var(--shadow-color);
            padding: 20px;
        }
        
        .request-section h2,
        .response-section h2 {
            margin-bottom: 20px;
        }
        
        .url-section {
            display: flex;
            gap: 10px;
            margin-bottom: 20px;
            align-items: center;
        }
        
        .method-select {
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            background-color: var(--card-background);
            color: var(--text-color);
            font-size: 14px;
            min-width: 100px;
        }
        
        .url-input {
            flex: 1;
            padding: 8px 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            background-color: var(--card-background);
            color: var(--text-color);
            font-size: 14px;
        }
        
        .send-btn {
            padding: 8px 20px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }
        
        .send-btn:hover {
            background-color: var(--secondary-color);
        }
        
        .send-btn:disabled {
            background-color: #ccc;
            cursor: not-allowed;
        }
        
        .tabs {
            display: flex;
            border-bottom: 1px solid var(--border-color);
            margin-bottom: 15px;
        }
        
        .tab {
            padding: 10px 20px;
            cursor: pointer;
            border-bottom: 2px solid transparent;
            transition: all 0.3s;
            color: var(--text-color);
        }
        
        .tab.active {
            border-bottom-color: var(--primary-color);
            color: var(--primary-color);
        }
        
        .tab-content {
            display: none;
        }
        
        .tab-content.active {
            display: block;
        }
        
        .params-table {
            width: 100%;
            border-collapse: collapse;
        }
        
        .params-table th,
        .params-table td {
            padding: 8px;
            border: 1px solid var(--border-color);
            text-align: left;
        }
        
        .params-table th {
            background-color: var(--background-color);
            font-weight: bold;
        }
        
        .params-table input {
            width: 100%;
            padding: 4px 8px;
            border: none;
            background: transparent;
            color: var(--text-color);
            position: relative;
        }
        
        .params-table input:focus {
            outline: 1px solid var(--primary-color);
        }
        
        .autocomplete-container {
            position: relative;
            display: inline-block;
            width: 100%;
        }
        
        .autocomplete-suggestions {
            position: absolute;
            top: 100%;
            left: 0;
            right: 0;
            background-color: var(--card-background);
            border: 1px solid var(--border-color);
            border-top: none;
            border-radius: 0 0 4px 4px;
            max-height: 200px;
            overflow-y: auto;
            z-index: 1000;
            display: none;
            box-shadow: 0 2px 8px var(--shadow-color);
        }
        
        .autocomplete-suggestion {
            padding: 8px 12px;
            cursor: pointer;
            border-bottom: 1px solid var(--border-color);
            color: var(--text-color);
            font-size: 14px;
        }
        
        .autocomplete-suggestion:last-child {
            border-bottom: none;
        }
        
        .autocomplete-suggestion:hover,
        .autocomplete-suggestion.selected {
            background-color: var(--primary-color);
            color: white;
        }
        
        .suggestion-key {
            font-weight: bold;
        }
        
        .suggestion-value {
            color: var(--text-color);
            opacity: 0.7;
            font-size: 12px;
            margin-left: 8px;
        }
        
        .autocomplete-suggestion:hover .suggestion-value,
        .autocomplete-suggestion.selected .suggestion-value {
            color: rgba(255, 255, 255, 0.8);
        }
        
        .add-param-btn {
            margin-top: 10px;
            padding: 6px 12px;
            background-color: var(--success-color);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .remove-param-btn {
            background-color: var(--error-color);
            color: white;
            border: none;
            border-radius: 2px;
            cursor: pointer;
            padding: 2px 6px;
            font-size: 12px;
        }
        
        .headers-section textarea,
        .body-section textarea {
            width: 100%;
            min-height: 150px;
            padding: 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-family: 'Consolas', monospace;
            font-size: 14px;
            background-color: var(--card-background);
            color: var(--text-color);
            resize: vertical;
        }
        
        .response-section {
            background-color: var(--card-background);
            border-radius: 8px;
            box-shadow: 0 4px 6px var(--shadow-color);
            padding: 20px;
        }
        
        .response-status {
            display: flex;
            gap: 20px;
            margin-bottom: 15px;
            padding: 10px;
            background-color: var(--background-color);
            border-radius: 4px;
        }
        
        .status-item {
            display: flex;
            flex-direction: column;
            align-items: center;
        }
        
        .status-label {
            font-size: 12px;
            color: var(--text-color);
            opacity: 0.7;
        }
        
        .status-value {
            font-weight: bold;
            font-size: 14px;
        }
        
        .status-200 { color: var(--success-color); }
        .status-400 { color: var(--warning-color); }
        .status-500 { color: var(--error-color); }
        
        .response-content {
            border: 1px solid var(--border-color);
            border-radius: 4px;
            max-height: 400px;
            overflow: auto;
        }
        
        .response-headers,
        .response-body {
            padding: 12px;
            font-family: 'Consolas', monospace;
            font-size: 14px;
            white-space: pre-wrap;
            word-wrap: break-word;
        }
        
        .loading {
            display: flex;
            align-items: center;
            gap: 10px;
            color: var(--primary-color);
        }
        
        .spinner {
            width: 16px;
            height: 16px;
            border: 2px solid var(--border-color);
            border-top: 2px solid var(--primary-color);
            border-radius: 50%;
            animation: spin 1s linear infinite;
        }
        
        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }
        
        .copy-response-btn {
            margin-top: 10px;
            padding: 6px 12px;
            background-color: var(--primary-color);
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
        }
        
        .bulk-edit-checkbox {
            display: flex;
            align-items: center;
            cursor: pointer;
            font-size: 14px;
            color: var(--text-color);
            margin-bottom: 10px;
            user-select: none;
        }
        
        .bulk-edit-checkbox input[type="checkbox"] {
            display: none;
        }
        
        .bulk-edit-checkbox .checkmark {
            width: 18px;
            height: 18px;
            border: 2px solid var(--border-color);
            border-radius: 3px;
            margin-right: 8px;
            position: relative;
            transition: all 0.3s;
        }
        
        .bulk-edit-checkbox input[type="checkbox"]:checked + .checkmark {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        .bulk-edit-checkbox input[type="checkbox"]:checked + .checkmark::after {
            content: '';
            position: absolute;
            left: 5px;
            top: 2px;
            width: 4px;
            height: 8px;
            border: solid white;
            border-width: 0 2px 2px 0;
            transform: rotate(45deg);
        }
        
        .bulk-edit-textarea {
            width: 100%;
            min-height: 100px;
            padding: 12px;
            border: 1px solid var(--border-color);
            border-radius: 4px;
            font-family: 'Consolas', monospace;
            font-size: 14px;
            background-color: var(--card-background);
            color: var(--text-color);
            display: none;
        }
        
        .bulk-edit-textarea.show {
            display: block;
        }
    </style>
</head>
<body>
    <header>
        <div class="header-container">
            <div class="header-left">
                <div class="logo">
                    <span><a href="https://geekdaxue.co/" target="_blank"><img src="https://geekdaxue.co/static/images/logo_platypus.png" height="30px"></a></span>
                </div>
                <nav class="main-navigation">
                    <div class="nav-item dropdown">
                        <a href="#" class="nav-link">
                            JSON工具 <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="dropdown-menu">
                            <a href="../json/index.html">JSON 格式化</a>
                            <a href="../json/parser.html">JSON 格式校验</a>
                            <a href="../json/excel.html">JSON 转 Excel/CSV</a>
                            <a href="../json/jsonxml.html">JSON 与 XML 转换</a>
                            <a href="../json/editor.html">JSON 编辑器</a>
                        </div>
                    </div>
                    <div class="nav-item dropdown">
                        <a href="#" class="nav-link">
                            编码转换 <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="dropdown-menu">
                            <a href="../coding/base64.html">Base64 编码</a>
                            <a href="../coding/urlencoding.html">URL 编码</a>
                            <a href="../coding/md5.html">MD5 加密</a>
                            <a href="../coding/unicode.html">Unicode 转换</a>
                            <a href="../coding/hex_convert.html">进制转换</a>
                        </div>
                    </div>
                    <div class="nav-item dropdown">
                        <a href="#" class="nav-link">
                            文本工具 <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="dropdown-menu">
                            <a href="../txt/diff.html">文本对比</a>
                            <a href="../txt/replace.html">文本替换</a>
                            <a href="../txt/remove.html">空白行移除</a>
                            <a href="../txt/cn_trans.html">繁简体转换</a>
                        </div>
                    </div>
                    <div class="nav-item dropdown">
                        <a href="#" class="nav-link">
                            图片工具 <i class="fas fa-chevron-down"></i>
                        </a>
                        <div class="dropdown-menu">
                            <a href="../img/2svg.html">图片转 SVG</a>
                            <a href="../img/qr_code.html">二维码生成</a>
                            <a href="../img/barcode.html">条形码生成</a>
                        </div>
                    </div>
                </nav>
            </div>
            <div class="header-controls">
                <div class="theme-toggle">
                    <input type="checkbox" id="theme-switch" class="theme-switch">
                    <label for="theme-switch" class="theme-switch-label">
                        <i class="fas fa-sun"></i>
                        <i class="fas fa-moon"></i>
                        <span class="slider"></span>
                    </label>
                </div>
                <div class="share-button" id="share-button" title="分享给朋友">
                    <i class="fas fa-share-alt"></i>
                    <span>分享</span>
                </div>
            </div>
        </div>
    </header>
    <div class="container">
        <div id="privacy-notice" class="privacy-notice">
            <div class="privacy-notice-content">
                <i class="fas fa-shield-alt"></i>
                <p>安全提示：您的数据仅在本地浏览器中处理，不会上传到服务器，请放心使用！</p>
                <button id="close-notice" class="close-notice" title="关闭提示">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        </div>
        
        <main>
            <div class="http-container">
                <!-- 请求配置区域 -->
                <div class="request-section">
                    <h2>HTTP 请求配置</h2>
                    
                    <!-- URL 和方法 -->
                    <div class="url-section">
                        <select id="method-select" class="method-select">
                            <option value="GET">GET</option>
                            <option value="POST">POST</option>
                            <option value="PUT">PUT</option>
                            <option value="DELETE">DELETE</option>
                            <option value="PATCH">PATCH</option>
                            <option value="HEAD">HEAD</option>
                            <option value="OPTIONS">OPTIONS</option>
                        </select>
                        <input type="text" id="url-input" class="url-input" placeholder="" value="">
                        <button id="send-btn" class="send-btn">
                            <i class="fas fa-paper-plane"></i> 发送
                        </button>
                    </div>
                    
                    <!-- 参数配置标签页 -->
                    <div class="tabs">
                        <div class="tab active" data-tab="params">
                            <i class="fas fa-list"></i> Query Params
                        </div>
                        <div class="tab" data-tab="headers">
                            <i class="fas fa-tags"></i> Headers
                        </div>
                        <div class="tab" data-tab="body">
                            <i class="fas fa-file-alt"></i> Body
                        </div>
                        <div class="tab" data-tab="cookies">
                            <i class="fas fa-cookie-bite"></i> Cookies
                        </div>
                    </div>
                    
                    <!-- Query Parameters -->
                    <div id="params-content" class="tab-content active">
                        <table class="params-table" id="params-table">
                            <thead>
                                <tr>
                                    <th style="width: 40%">Key</th>
                                    <th style="width: 40%">Value</th>
                                    <th style="width: 15%">Description</th>
                                    <th style="width: 5%">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td><input type="text" placeholder="Key"></td>
                                    <td><input type="text" placeholder="Value"></td>
                                    <td><input type="text" placeholder="Description"></td>
                                    <td><button class="remove-param-btn" onclick="removeParamRow(this)">×</button></td>
                                </tr>
                            </tbody>
                        </table>
                        <button class="add-param-btn" onclick="addParamRow()">+ 添加参数</button>
                    </div>
                    
                    <!-- Headers -->
                    <div id="headers-content" class="tab-content">
                        <label class="bulk-edit-checkbox">
                            <input type="checkbox" id="bulk-edit-headers">
                            <span class="checkmark"></span>
                            批量编辑
                        </label>
                        <table class="params-table" id="headers-table">
                            <thead>
                                <tr>
                                    <th style="width: 40%">Key</th>
                                    <th style="width: 40%">Value</th>
                                    <th style="width: 15%">Description</th>
                                    <th style="width: 5%">操作</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr>
                                    <td>
                                        <div class="autocomplete-container">
                                            <input type="text" placeholder="Key" class="header-key-input">
                                            <div class="autocomplete-suggestions"></div>
                                        </div>
                                    </td>
                                    <td>
                                        <div class="autocomplete-container">
                                            <input type="text" placeholder="Value" class="header-value-input">
                                            <div class="autocomplete-suggestions"></div>
                                        </div>
                                    </td>
                                    <td><input type="text" placeholder="Description"></td>
                                    <td><button class="remove-param-btn" onclick="removeHeaderRow(this)">×</button></td>
                                </tr>
                            </tbody>
                        </table>
                        <textarea id="bulk-headers-textarea" class="bulk-edit-textarea" placeholder="批量编辑格式：\nKey1: Value1\nKey2: Value2\n..."></textarea>
                        <button class="add-param-btn" onclick="addHeaderRow()">+ 添加 Header</button>
                    </div>
                    
                    <!-- Body -->
                    <div id="body-content" class="tab-content">
                        <div class="body-section">
                            <textarea id="request-body" placeholder='{\n  "msg": "操作成功",\n  "data": null,\n  "code": 200\n}'>{"msg": "操作成功", "data": null, "code": 200}</textarea>
                        </div>
                    </div>
                    
                    <!-- Cookies -->
                    <div id="cookies-content" class="tab-content">
                        <p style="color: var(--text-color); opacity: 0.7;">Cookie 管理功能开发中...</p>
                    </div>
                </div>
                
                <!-- 响应结果区域 -->
                <div class="response-section">
                    <h2>响应结果</h2>
                    
                    <div id="response-status" class="response-status" style="display: none;">
                        <div class="status-item">
                            <span class="status-label">状态码</span>
                            <span id="response-status-code" class="status-value"></span>
                        </div>
                        <div class="status-item">
                            <span class="status-label">响应时间</span>
                            <span id="response-time" class="status-value">6.29 s</span>
                        </div>
                        <div class="status-item">
                            <span class="status-label">响应大小</span>
                            <span id="response-size" class="status-value">252 B</span>
                        </div>
                    </div>
                    
                    <div id="loading-indicator" class="loading" style="display: none;">
                        <div class="spinner"></div>
                        <span>正在发送请求...</span>
                    </div>
                    
                    <div class="tabs">
                        <div class="tab active" data-tab="response-body">
                            <i class="fas fa-file-alt"></i> Body
                        </div>
                        <div class="tab" data-tab="response-headers">
                            <i class="fas fa-tags"></i> Headers (6)
                        </div>
                        <div class="tab" data-tab="test-results">
                            <i class="fas fa-check-circle"></i> Test Results
                        </div>
                        <div class="tab" data-tab="visualize">
                            <i class="fas fa-chart-bar"></i> Visualize
                        </div>
                    </div>
                    
                    <div id="response-body-content" class="tab-content active">
                        <div class="tabs">
                            <div class="tab active" data-tab="pretty">
                                <i class="fas fa-eye"></i> Pretty
                            </div>
                            <div class="tab" data-tab="raw">
                                <i class="fas fa-code"></i> Raw
                            </div>
                            <div class="tab" data-tab="preview">
                                <i class="fas fa-search"></i> Preview
                            </div>
                        </div>
                        <div class="response-content">
                            <div id="response-body" class="response-body">点击发送按钮开始请求...</div>
                        </div>
                        <button id="copy-response-btn" class="copy-response-btn" style="display: none;">
                            <i class="fas fa-copy"></i> 复制响应
                        </button>
                    </div>
                    
                    <div id="response-headers-content" class="tab-content">
                        <div class="response-content">
                            <div id="response-headers" class="response-headers">暂无响应头信息</div>
                        </div>
                    </div>
                    
                    <div id="test-results-content" class="tab-content">
                        <p style="color: var(--text-color); opacity: 0.7;">测试结果功能开发中...</p>
                    </div>
                    
                    <div id="visualize-content" class="tab-content">
                        <p style="color: var(--text-color); opacity: 0.7;">可视化功能开发中...</p>
                    </div>
                </div>
            </div>
        </main>
    </div>
    <footer>
            <div class="footer-container">
                <div class="footer-main">
                    <div class="footer-section about-us">
                        <h3>关于我们</h3>
                        <p>我们提供一系列高效、便捷的在线工具，帮助开发者、非技术人员提高工作效率，解决日常开发中遇到的各种问题。</p>
                        <p>Build With <i class="fa-solid fa-heart" style="color: red;"></i> For SF.</p>
                    </div>
                    <div class="footer-section links">
                        <h3>工具导航</h3>
                        <div class="links-columns">
                            <ul>
                                <li><a href="../json/index.html">JSON 工具</a></li>
                                <li><a href="../img/index.html">图片处理</a></li>
                                <li><a href="#">开发工具</a></li>
                            </ul>
                            <ul>
                                <li><a href="../coding/index.html">编码转换</a></li>
                                <li><a href="../txt/index.html">文本工具</a></li>
                            </ul>
                        </div>
                    </div>
                    <div class="footer-section contact">
                        <h3>联系我们</h3>
                        <div class="social-icons">
                            <a href="#" title="GitHub"><i class="fab fa-github"></i></a>
                            <a href="#" title="Twitter"><i class="fab fa-twitter"></i></a>
                            <a href="#" title="WeChat"><i class="fab fa-weixin"></i></a>
                            <a href="mailto:example@example.com" title="Email"><i class="fas fa-envelope"></i></a>
                        </div>
                        <p>如有问题或建议，请随时联系我们</p>
                    </div>
                </div>
                <div class="footer-bottom">
                    <div class="footer-legal">
                        <a href="#">使用条款</a>
                        <a href="#">隐私政策</a>
                    </div>
                </div>
            </div>
        </footer>
    
    <div id="copy-notification" class="copy-notification">已复制到剪贴板！</div>
    <div id="share-notification" class="copy-notification">已复制网址，赶快让更多的小伙伴知道我吧！</div>
    
    <script>
        // 将需要全局访问的函数附加到 window 对象上
        window.addParamRow = function() {
            const table = document.getElementById('params-table').getElementsByTagName('tbody')[0];
            const newRow = table.insertRow();
            newRow.innerHTML = `
                <td><input type="text" placeholder="Key"></td>
                <td><input type="text" placeholder="Value"></td>
                <td><input type="text" placeholder="Description"></td>
                <td><button class="remove-param-btn" onclick="removeParamRow(this)">×</button></td>
            `;
        }
        
        window.removeParamRow = function(btn) {
            const row = btn.closest('tr');
            row.remove();
        }
        
        window.addHeaderRow = function() {
            const table = document.getElementById('headers-table').getElementsByTagName('tbody')[0];
            const newRow = table.insertRow();
            newRow.innerHTML = `
                <td>
                    <div class="autocomplete-container">
                        <input type="text" placeholder="Key" class="header-key-input">
                        <div class="autocomplete-suggestions"></div>
                    </div>
                </td>
                <td>
                    <div class="autocomplete-container">
                        <input type="text" placeholder="Value" class="header-value-input">
                        <div class="autocomplete-suggestions"></div>
                    </div>
                </td>
                <td><input type="text" placeholder="Description"></td>
                <td><button class="remove-param-btn" onclick="removeHeaderRow(this)">×</button></td>
            `;
            
            // 为新添加的输入框绑定自动完成事件
            const keyInput = newRow.querySelector('.header-key-input');
            const valueInput = newRow.querySelector('.header-value-input');
            // setupHeaderAutocomplete is not defined, so comment it out
            // setupHeaderAutocomplete(keyInput, valueInput);
        }
        
        window.removeHeaderRow = function(btn) {
            const row = btn.closest('tr');
            row.remove();
        }

        document.addEventListener('DOMContentLoaded', function() {
            const sendBtn = document.getElementById('send-btn');
            const methodSelect = document.getElementById('method-select');
            const urlInput = document.getElementById('url-input');
            const responseStatusContainer = document.getElementById('response-status');
            const responseStatusCode = document.getElementById('response-status-code');
            const responseTime = document.getElementById('response-time');
            const responseSize = document.getElementById('response-size');
            const responseHeadersContainer = document.getElementById('response-headers');
            const responseBodyContainer = document.getElementById('response-body');
            const loadingIndicator = document.getElementById('loading-indicator');

            sendBtn.addEventListener('click', async () => {
                const method = methodSelect.value;
                let url = urlInput.value.trim();

                if (!url) {
                    alert('请输入请求 URL');
                    return;
                }

                // 处理 Query Params
                const params = getParamsFromTable('params-table');
                if (method === 'GET' && params.length > 0) {
                    const queryString = new URLSearchParams(params.map(p => [p.key, p.value])).toString();
                    url += (url.includes('?') ? '&' : '?') + queryString;
                }

                // 处理 Headers
                const headers = new Headers();
                const headerParams = getParamsFromTable('headers-table');
                headerParams.forEach(h => {
                    if (h.key) headers.append(h.key, h.value);
                });

                // 处理 Body
                const bodyTab = document.querySelector('.tab[data-tab="body"]').classList.contains('active');
                let body = null;
                if (['POST', 'PUT', 'PATCH'].includes(method) && bodyTab) {
                    body = document.getElementById('body-textarea').value;
                }

                const requestOptions = {
                    method: method,
                    headers: headers,
                    body: body
                };

                // 发送请求
                loadingIndicator.style.display = 'flex';
                responseStatusContainer.style.display = 'none';
                sendBtn.disabled = true;
                const startTime = Date.now();

                try {
                    const response = await fetch(url, requestOptions);
                    const endTime = Date.now();

                    // 显示响应状态
                    responseStatusContainer.style.display = 'flex';
                    responseStatusCode.textContent = `${response.status} ${response.statusText}`;
                    responseStatusCode.className = `status-value status-${String(response.status)[0]}00`;
                    responseTime.textContent = `${endTime - startTime} ms`;

                    // 显示响应头
                    let headersStr = '';
                    response.headers.forEach((value, key) => {
                        headersStr += `${key}: ${value}\n`;
                    });
                    responseHeadersContainer.textContent = headersStr;

                    // 显示响应体
                    const responseBody = await response.text();
                    responseBodyContainer.textContent = responseBody;
                    const sizeInBytes = new Blob([responseBody]).size;
                    responseSize.textContent = `${(sizeInBytes / 1024).toFixed(2)} KB`;

                } catch (error) {
                    responseStatusContainer.style.display = 'flex';
                    responseStatusCode.textContent = '请求失败';
                    responseStatusCode.className = 'status-value status-500';
                    responseBodyContainer.textContent = error.message;
                    responseTime.textContent = 'N/A';
                    responseSize.textContent = 'N/A';
                } finally {
                    loadingIndicator.style.display = 'none';
                    sendBtn.disabled = false;
                }
            });

            function getParamsFromTable(tableId) {
                const table = document.getElementById(tableId);
                const rows = table.querySelectorAll('tbody tr');
                const params = [];
                rows.forEach(row => {
                    const keyInput = row.querySelector('input[placeholder="Key"]');
                    const valueInput = row.querySelector('input[placeholder="Value"]');
                    if (keyInput && valueInput && keyInput.value.trim()) {
                        params.push({ key: keyInput.value.trim(), value: valueInput.value.trim() });
                    }
                });
                return params;
            }

            // 标签页切换
            document.querySelectorAll('.tabs .tab').forEach(tab => {
                tab.addEventListener('click', () => {
                    const targetContentId = tab.dataset.tab + '-content';
                    const targetContent = document.getElementById(targetContentId);

                    if (targetContent) {
                        // 移除同级元素的 active 类
                        tab.parentElement.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
                        // 隐藏所有同级 tab-content
                        const contentContainer = targetContent.parentElement;
                        contentContainer.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));

                        // 添加 active 类到当前点击的 tab 和对应的 content
                        tab.classList.add('active');
                        targetContent.classList.add('active');
                    }
                });
            });

            // 主题切换和分享功能
            const themeSwitch = document.getElementById('theme-switch');
            const privacyNotice = document.getElementById('privacy-notice');
            const closeNoticeBtn = document.getElementById('close-notice');
            const shareButton = document.getElementById('share-button');
            const copyNotification = document.getElementById('copy-notification');
            const shareNotification = document.getElementById('share-notification');
            
            // 检查本地存储中的主题设置
            if (localStorage.getItem('theme') === 'dark') {
                document.documentElement.setAttribute('data-theme', 'dark');
                themeSwitch.checked = true;
            }
            
            // 主题切换功能
            themeSwitch.addEventListener('change', function() {
                if (this.checked) {
                    document.documentElement.setAttribute('data-theme', 'dark');
                    localStorage.setItem('theme', 'dark');
                } else {
                    document.documentElement.removeAttribute('data-theme');
                    localStorage.setItem('theme', 'light');
                }
            });
            
            // 隐私提示框关闭功能
            closeNoticeBtn.addEventListener('click', function() {
                privacyNotice.style.display = 'none';
                localStorage.setItem('privacyNoticeClosed', 'true');
            });
            
            // 检查是否需要显示隐私提示
            if (localStorage.getItem('privacyNoticeClosed') === 'true') {
                privacyNotice.style.display = 'none';
            }
            
            // 分享功能
            shareButton.addEventListener('click', function() {
                const url = window.location.href;
                navigator.clipboard.writeText(url).then(function() {
                    showNotification(shareNotification);
                }).catch(function() {
                    console.error('复制失败');
                });
            });
            
            // 显示通知
            function showNotification(notification) {
                notification.classList.add('show');
                setTimeout(() => {
                    notification.classList.remove('show');
                }, 2000);
            }

            // 批量编辑功能
            document.getElementById('bulk-edit-headers').addEventListener('change', function() {
                const textarea = document.getElementById('bulk-headers-textarea');
                const table = document.getElementById('headers-table');
                
                if (this.checked) {
                    // 从表格提取数据到文本框
                    const rows = table.querySelectorAll('tbody tr');
                    let bulkText = '';
                    rows.forEach(row => {
                        const inputs = row.querySelectorAll('input');
                        if (inputs[0].value && inputs[1].value) {
                            bulkText += `${inputs[0].value}: ${inputs[1].value}\n`;
                        }
                    });
                    textarea.value = bulkText;
                    textarea.classList.add('show');
                    table.style.display = 'none';
                } else {
                    // 从文本框解析数据到表格
                    const lines = textarea.value.split('\n').filter(line => line.trim());
                    const tbody = table.querySelector('tbody');
                    tbody.innerHTML = '';
                    
                    lines.forEach(line => {
                        const [key, ...valueParts] = line.split(':');
                        if (key && valueParts.length > 0) {
                            const value = valueParts.join(':').trim();
                            const newRow = tbody.insertRow();
                            newRow.innerHTML = `
                                <td>
                                    <div class="autocomplete-container">
                                        <input type="text" value="${key.trim()}" placeholder="Key" class="header-key-input">
                                        <div class="autocomplete-suggestions"></div>
                                    </div>
                                </td>
                                <td>
                                    <div class="autocomplete-container">
                                        <input type="text" value="${value}" placeholder="Value" class="header-value-input">
                                        <div class="autocomplete-suggestions"></div>
                                    </div>
                                </td>
                                <td><input type="text" placeholder="Description"></td>
                                <td><button class="remove-param-btn" onclick="removeHeaderRow(this)">×</button></td>
                            `;
                            
                            // 为新添加的输入框绑定自动完成事件
                            const keyInput = newRow.querySelector('.header-key-input');
                            const valueInput = newRow.querySelector('.header-value-input');
                            // setupHeaderAutocomplete is not defined, so comment it out
                            // setupHeaderAutocomplete(keyInput, valueInput);
                        }
                    });
                }
            });
        });
        
        // 批量编辑功能
        document.getElementById('bulk-edit-headers').addEventListener('change', function() {
            const textarea = document.getElementById('bulk-headers-textarea');
            const table = document.getElementById('headers-table');
            
            if (this.checked) {
                // 从表格提取数据到文本框
                const rows = table.querySelectorAll('tbody tr');
                let bulkText = '';
                rows.forEach(row => {
                    const inputs = row.querySelectorAll('input');
                    if (inputs[0].value && inputs[1].value) {
                        bulkText += `${inputs[0].value}: ${inputs[1].value}\n`;
                    }
                });
                textarea.value = bulkText;
                textarea.classList.add('show');
                table.style.display = 'none';
            } else {
                // 从文本框解析数据到表格
                const lines = textarea.value.split('\n').filter(line => line.trim());
                const tbody = table.querySelector('tbody');
                tbody.innerHTML = '';
                
                lines.forEach(line => {
                    const [key, ...valueParts] = line.split(':');
                    if (key && valueParts.length > 0) {
                        const value = valueParts.join(':').trim();
                        const newRow = tbody.insertRow();
                        newRow.innerHTML = `
                            <td>
                                <div class="autocomplete-container">
                                    <input type="text" value="${key.trim()}" placeholder="Key" class="header-key-input">
                                    <div class="autocomplete-suggestions"></div>
                                </div>
                            </td>
                            <td>
                                <div class="autocomplete-container">
                                    <input type="text" value="${value}" placeholder="Value" class="header-value-input">
                                    <div class="autocomplete-suggestions"></div>
                                </div>
                            </td>
                            <td><input type="text" placeholder="Description"></td>
                            <td><button class="remove-param-btn" onclick="removeHeaderRow(this)">×</button></td>
                        `;
                        
                        // 为新添加的输入框绑定自动完成事件
                        const keyInput = newRow.querySelector('.header-key-input');
                        const valueInput = newRow.querySelector('.header-value-input');
                        setupHeaderAutocomplete(keyInput, valueInput);
                    }
                });
                
                // 如果没有行，添加一个空行
                if (tbody.children.length === 0) {
                    addHeaderRow();
                }
                
                textarea.classList.remove('show');
                table.style.display = 'table';
            }
        });
        
        // HTTP 请求发送功能
        document.getElementById('send-btn').addEventListener('click', function() {
            sendHttpRequest();
        });
        
        async function sendHttpRequest() {
            const method = document.getElementById('method-select').value;
            const url = document.getElementById('url-input').value.trim();
            const sendBtn = document.getElementById('send-btn');
            const loadingIndicator = document.getElementById('loading-indicator');
            const responseStatus = document.getElementById('response-status');
            const responseBody = document.getElementById('response-body');
            const responseHeaders = document.getElementById('response-headers');
            const copyResponseBtn = document.getElementById('copy-response-btn');
            
            if (!url) {
                alert('请输入请求URL');
                return;
            }
            
            // 收集查询参数
            const params = new URLSearchParams();
            const paramRows = document.querySelectorAll('#params-table tbody tr');
            paramRows.forEach(row => {
                const inputs = row.querySelectorAll('input');
                if (inputs[0].value && inputs[1].value) {
                    params.append(inputs[0].value, inputs[1].value);
                }
            });
            
            // 收集请求头
            const headers = {};
            const headerRows = document.querySelectorAll('#headers-table tbody tr');
            headerRows.forEach(row => {
                const inputs = row.querySelectorAll('input');
                if (inputs[0].value && inputs[1].value) {
                    headers[inputs[0].value] = inputs[1].value;
                }
            });
            
            // 构建完整URL
            let fullUrl = url;
            if (params.toString()) {
                fullUrl += (url.includes('?') ? '&' : '?') + params.toString();
            }
            
            // 准备请求配置
            const requestConfig = {
                method: method,
                headers: headers
            };
            
            // 添加请求体（如果需要）
            if (['POST', 'PUT', 'PATCH'].includes(method)) {
                const bodyContent = document.getElementById('request-body').value.trim();
                if (bodyContent) {
                    requestConfig.body = bodyContent;
                }
            }
            
            // 显示加载状态
            sendBtn.disabled = true;
            loadingIndicator.style.display = 'flex';
            responseStatus.style.display = 'none';
            responseBody.textContent = '正在请求中...';
            responseHeaders.textContent = '正在请求中...';
            copyResponseBtn.style.display = 'none';
            
            const startTime = Date.now();
            
            try {
                // 发送请求
                const response = await fetch(fullUrl, requestConfig);
                const endTime = Date.now();
                const responseTime = ((endTime - startTime) / 1000).toFixed(2);
                
                // 获取响应文本
                const responseText = await response.text();
                
                // 更新状态信息
                document.getElementById('response-status-code').textContent = `${response.status} ${response.statusText}`;
                document.getElementById('response-status-code').className = `status-value status-${Math.floor(response.status / 100) * 100}`;
                document.getElementById('response-time').textContent = `${responseTime} s`;
                document.getElementById('response-size').textContent = formatBytes(new Blob([responseText]).size);
                
                // 显示响应体
                try {
                    const jsonResponse = JSON.parse(responseText);
                    responseBody.textContent = JSON.stringify(jsonResponse, null, 2);
                } catch {
                    responseBody.textContent = responseText;
                }
                
                // 显示响应头
                let headersText = '';
                response.headers.forEach((value, key) => {
                    headersText += `${key}: ${value}\n`;
                });
                responseHeaders.textContent = headersText || '无响应头信息';
                
                // 更新Headers标签页计数
                const headersTab = document.querySelector('[data-tab="response-headers"]');
                const headerCount = response.headers.size || 0;
                headersTab.innerHTML = `<i class="fas fa-tags"></i> Headers (${headerCount})`;
                
                responseStatus.style.display = 'flex';
                copyResponseBtn.style.display = 'inline-block';
                
            } catch (error) {
                console.error('请求失败:', error);
                responseBody.textContent = `请求失败: ${error.message}`;
                responseHeaders.textContent = '请求失败，无响应头信息';
                
                // 显示错误状态
                document.getElementById('response-status-code').textContent = 'Error';
                document.getElementById('response-status-code').className = 'status-value status-500';
                document.getElementById('response-time').textContent = '-';
                document.getElementById('response-size').textContent = '-';
                responseStatus.style.display = 'flex';
            } finally {
                // 隐藏加载状态
                sendBtn.disabled = false;
                loadingIndicator.style.display = 'none';
            }
        }
        
        // 复制响应内容
        document.getElementById('copy-response-btn').addEventListener('click', function() {
            const responseBody = document.getElementById('response-body').textContent;
            navigator.clipboard.writeText(responseBody).then(function() {
                showNotification(document.getElementById('copy-notification'));
            }).catch(function() {
                console.error('复制失败');
            });
        });
        
        // 格式化字节大小
        function formatBytes(bytes) {
            if (bytes === 0) return '0 B';
            const k = 1024;
            const sizes = ['B', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }
        
        // 显示通知函数
        function showNotification(notification) {
            notification.classList.add('show');
            setTimeout(() => {
                notification.classList.remove('show');
            }, 2000);
        }
        
        // HTTP Headers 自动完成数据（按字典序排序）
        const commonHeaders = {
            'Accept': ['application/json', 'application/xml', 'text/html', 'text/plain', '*/*'],
            'Accept-Charset': ['utf-8', 'iso-8859-1', 'utf-16'],
            'Accept-Encoding': ['gzip', 'deflate', 'br', 'gzip, deflate', 'gzip, deflate, br'],
            'Accept-Language': ['en-US', 'zh-CN', 'en-US,en;q=0.9', 'zh-CN,zh;q=0.9,en;q=0.8'],
            'Access-Control-Allow-Credentials': ['true', 'false'],
            'Access-Control-Allow-Headers': ['Content-Type', 'Authorization', 'X-Requested-With'],
            'Access-Control-Allow-Methods': ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'GET, POST, PUT, DELETE'],
            'Access-Control-Allow-Origin': ['*', 'https://example.com', 'null'],
            'Access-Control-Max-Age': ['86400', '3600', '7200'],
            'Authorization': ['Bearer token', 'Basic base64credentials', 'Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...'],
            'Cache-Control': ['no-cache', 'no-store', 'max-age=3600', 'public', 'private'],
            'Connection': ['keep-alive', 'close'],
            'Content-Encoding': ['gzip', 'deflate', 'br'],
            'Content-Length': ['0', '1024', '2048'],
            'Content-Type': ['application/json', 'application/x-www-form-urlencoded', 'multipart/form-data', 'text/html', 'text/plain', 'application/xml'],
            'Cookie': ['sessionid=abc123', 'csrftoken=xyz789', 'user_id=12345'],
            'Host': ['api.example.com', 'localhost:3000', 'www.example.com'],
            'If-Modified-Since': ['Wed, 21 Oct 2015 07:28:00 GMT'],
            'If-None-Match': ['"686897696a7c876b7e"'],
            'Origin': ['https://example.com', 'http://localhost:3000'],
            'Referer': ['https://example.com/page', 'https://www.google.com'],
            'User-Agent': ['Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36', 'PostmanRuntime/7.28.4', 'curl/7.68.0'],
            'X-API-Key': ['your-api-key-here', 'sk-1234567890abcdef'],
            'X-Forwarded-For': ['203.0.113.195', '127.0.0.1'],
            'X-Requested-With': ['XMLHttpRequest'],
            'X-CSRF-Token': ['token-value-here']
        };
        
        // 设置Header自动完成功能
        function setupHeaderAutocomplete(keyInput, valueInput) {
            const keySuggestions = keyInput.parentElement.querySelector('.autocomplete-suggestions');
            const valueSuggestions = valueInput.parentElement.querySelector('.autocomplete-suggestions');
            
            let selectedIndex = -1;
            
            // Key输入框自动完成
            keyInput.addEventListener('input', function() {
                const value = this.value.toLowerCase();
                const suggestions = Object.keys(commonHeaders).filter(header => 
                    header.toLowerCase().includes(value)
                ).sort();
                
                showSuggestions(keySuggestions, suggestions, value, (selectedValue) => {
                    keyInput.value = selectedValue;
                    keySuggestions.style.display = 'none';
                    selectedIndex = -1;
                    
                    // 自动填充对应的Value建议
                    if (commonHeaders[selectedValue] && commonHeaders[selectedValue].length > 0) {
                        valueInput.value = commonHeaders[selectedValue][0];
                    }
                    keyInput.focus();
                });
                
                selectedIndex = -1;
            });
            
            // Value输入框自动完成
            valueInput.addEventListener('input', function() {
                const keyValue = keyInput.value;
                const inputValue = this.value.toLowerCase();
                
                if (commonHeaders[keyValue]) {
                    const suggestions = commonHeaders[keyValue].filter(val => 
                        val.toLowerCase().includes(inputValue)
                    );
                    
                    showSuggestions(valueSuggestions, suggestions, inputValue, (selectedValue) => {
                        valueInput.value = selectedValue;
                        valueSuggestions.style.display = 'none';
                        selectedIndex = -1;
                        valueInput.focus();
                    });
                }
                
                selectedIndex = -1;
            });
            
            // 键盘导航
            function handleKeyNavigation(input, suggestions, suggestionsList) {
                input.addEventListener('keydown', function(e) {
                    const items = suggestions.querySelectorAll('.autocomplete-suggestion');
                    
                    if (e.key === 'ArrowDown') {
                        e.preventDefault();
                        selectedIndex = Math.min(selectedIndex + 1, items.length - 1);
                        updateSelection(items);
                    } else if (e.key === 'ArrowUp') {
                        e.preventDefault();
                        selectedIndex = Math.max(selectedIndex - 1, -1);
                        updateSelection(items);
                    } else if (e.key === 'Enter') {
                        e.preventDefault();
                        if (selectedIndex >= 0 && items[selectedIndex]) {
                            items[selectedIndex].click();
                        }
                    } else if (e.key === 'Escape') {
                        suggestions.style.display = 'none';
                        selectedIndex = -1;
                    }
                });
            }
            
            function updateSelection(items) {
                items.forEach((item, index) => {
                    item.classList.toggle('selected', index === selectedIndex);
                });
            }
            
            handleKeyNavigation(keyInput, keySuggestions);
            handleKeyNavigation(valueInput, valueSuggestions);
            
            // 点击外部关闭建议
            document.addEventListener('click', function(e) {
                if (!keyInput.contains(e.target) && !keySuggestions.contains(e.target)) {
                    keySuggestions.style.display = 'none';
                }
                if (!valueInput.contains(e.target) && !valueSuggestions.contains(e.target)) {
                    valueSuggestions.style.display = 'none';
                }
                selectedIndex = -1;
            });
        }
        
        // 显示建议列表
        function showSuggestions(container, suggestions, inputValue, onSelect) {
            container.innerHTML = '';
            
            if (suggestions.length === 0 || (suggestions.length === 1 && suggestions[0].toLowerCase() === inputValue)) {
                container.style.display = 'none';
                return;
            }
            
            suggestions.forEach(suggestion => {
                const div = document.createElement('div');
                div.className = 'autocomplete-suggestion';
                
                // 高亮匹配的部分
                const regex = new RegExp(`(${inputValue})`, 'gi');
                const highlightedText = suggestion.replace(regex, '<strong>$1</strong>');
                
                div.innerHTML = `<span class="suggestion-key">${highlightedText}</span>`;
                
                div.addEventListener('click', function() {
                    onSelect(suggestion);
                });
                
                container.appendChild(div);
            });
            
            container.style.display = 'block';
        }
        
        // 初始化现有的Header输入框
        document.addEventListener('DOMContentLoaded', function() {
            const headerKeyInputs = document.querySelectorAll('.header-key-input');
            const headerValueInputs = document.querySelectorAll('.header-value-input');
            
            headerKeyInputs.forEach((keyInput, index) => {
                const valueInput = headerValueInputs[index];
                if (valueInput) {
                    setupHeaderAutocomplete(keyInput, valueInput);
                }
            });
        });
        
        // 百度统计
        var _hmt = _hmt || [];
        (function() {
          var hm = document.createElement("script");
          hm.src = "https://hm.baidu.com/hm.js?3615c6485313357fe26e486bf42d9ec2";
          var s = document.getElementsByTagName("script")[0]; 
          s.parentNode.insertBefore(hm, s);
        })();
    </script>
</body>
</html>